const jsonwebtoken = require('jsonwebtoken');
const BaseController = require('../core/BaseController');
const config = require('../../config/config.jwt');
const permissionConfig = require('../../config/config.permission');

module.exports = class extends BaseController {
  constructor(props) {
    super(props);
    this.tableName = 'user';
  }

  async signin() {
    const { ctx, app, service } = this;
    const { username, password } = ctx.request.body;
    if(!username || !password){
      return ctx.fail('账号或者密码不能为空', 1004);
    }
    let user = await app.mysql.get(this.tableName, { username, password, delete_time:null });
    if(!user){
      return ctx.fail('找不到该用户', 1006);
    }
    user = ctx.helper.toPlainObject(user);
    let token = jsonwebtoken.sign({ id: user.id, username: user.username, authority: user.authority, role_id: user.role_id }, config.secret, { expiresIn: config.exp });
    user.token = token;
    return user ? ctx.success(user) : ctx.fail('密码错误', 1002);
  }

  async insert() {
    const { ctx, app } = this;
    const { username } = ctx.request.body;
    let rs = await app.mysql.get(this.tableName, { username });
    if (rs) {
      return ctx.fail('账号已被注册', 1003);
    }
    rs = await app.mysql.insert(this.tableName, { ...ctx.request.body, create_time: Date.now() });
    return rs.insertId > 0 ? ctx.success(rs.insertId) : ctx.fail('新增失败');
  }

  async updateRole() {
    const { ctx, app } = this;
    const { userIds, roleIds } = ctx.request.body;
    let rs = null;
    if (!Array.isArray(roleIds)) {
      roleIds = JSON.parse(roleIds);
    }
    if (roleIds) {
      const list = await app.mysql.select('role_permission', {
        where: { delete_time: null, role_id:roleIds }
      });
      let ids = list.map(item => item.permission_id);
      if(Array.isArray(ids)){
        ids = Array.from(new Set(ids));
      }
      rs = await app.mysql.beginTransactionScope(async conn => {
        try {
          if (!Array.isArray(userIds)) {
            userIds = JSON.parse(userIds);
          }
          for (let i = 0; i < userIds.length; i++) {
            await conn.delete('user_permission', { user_id: userIds[i] });
            for (let j = 0; j < ids.length; j++) {
              await conn.insert('user_permission', { permission_id: ids[j], user_id: userIds[i] });
            }
            await app.mysql.update(this.tableName, { id: userIds[i], role_ids: roleIds.join(',') });
          }
          return true;
        } catch (error) { 
          return false;
        }

      });
    }
    return rs ? ctx.success() : ctx.fail('更新失败');
  }



  // async signup() {
  //   const { ctx, app } = this;
  //   const { username, password } = ctx.request.body;
  //   let rs = await app.mysql.get(this.tableName, { username });
  //   if (rs) {
  //     return ctx.fail('账号名称已被注册', 1003);
  //   }
  //   rs = await app.mysql.insert(this.tableName, { username, password, create_time: Date.now() })
  //   let user = await app.mysql.get(this.tableName, { username, password });
  //   user = ctx.helper.lodash.toPlainObject(user);
  //   user.token = jsonwebtoken.sign({ id: user.id, username: user.username, authority: user.authority }, config.secret, { expiresIn: config.exp });
  //   return user ? ctx.success(user) : ctx.fail();
  // }

  async updateNickname() {
    const { ctx, app } = this;
    const { nickname } = ctx.request.body;
    const rs = await app.mysql.update(this.tableName, { nickname, id: ctx.user.id });
    return rs.affectedRows > 0 ? ctx.success() : ctx.fail('修改昵称失败');
  }

  async updatePassword() {
    const { ctx, app } = this;
    const { password, new_password } = ctx.request.body;
    let rs;
    if (await app.mysql.get(this.tableName, { username: ctx.user.username, password })) {
      rs = await app.mysql.update(this.tableName, { password: new_password, id: ctx.user.id });
    } else {
      return ctx.fail('密码错误', 1002);
    }
    return rs.affectedRows > 0 ? ctx.success() : ctx.fail('更新密码失败');
  }

  async info() {
    const { ctx, service } = this;
    const id = ctx.query.id;
    const user = await service.user.info(id);
    return user ? ctx.success(user) : ctx.fail();
  }

  async page() {
    const { ctx, app } = this;
    let { currentPage = 1, pageSize = 2, key = '' } = ctx.query;
    pageSize = parseInt(pageSize);
    const all = await app.mysql.query(`select * from ${this.tableName} where delete_time is null and authority = '' and username like "%${key}%"`);
    const list = await app.mysql.query(`select * from ${this.tableName} where delete_time is null and authority = '' and username like "%${key}%" order by create_time desc limit ${(currentPage - 1) * pageSize}, ${pageSize}`);
    for(let i = 0; i < list.length; i++){
      if(list[i].role_ids) {
        let roleList = await app.mysql.query(`select * from role where id in (${list[i].role_ids})`);
        if(roleList){
          list[i].role = roleList.map(role => role.name).join(',');
        }
      }
    }
    const count = all.length;
    const total = Math.ceil(count / pageSize);
    return list ? ctx.success({ currentPage, total, count, list }) : ctx.fail('查询分页失败');
  }

}

